import React from 'react';
import { Card, Table, Form, Input, Button, Space, DatePicker, Select } from 'antd';
import dayjs from 'dayjs';

// 模仿 admin-web 的 UserMachineAlarm.vue：
// - 支持搜索：时间范围、用户名称、设备编号、告警类型
// - 列表展示：用户、设备编号、类型、货道、订单号、告警码、信息、时间
// - 分页与加载状态（模拟数据）
export default function UserMachineAlarm() {
  const [form] = Form.useForm();

  // 告警类型字典（模拟）
  const alarmTypeList = React.useMemo(() => ([
    { label: '设备故障', value: 1 },
    { label: '缺货报警', value: 2 },
    { label: '温度异常', value: 3 },
    { label: '门禁报警', value: 4 },
  ]), []);

  const getLabel = (val) => {
    const f = alarmTypeList.find(a => String(a.value) === String(val));
    return f ? f.label : val;
  };

  // 默认最近 7 天（含今天），与 Vue 中 getDefault 一致
  const getDefaultRange = () => [dayjs().subtract(6, 'day').startOf('day'), dayjs().endOf('day')];
  const [dateRange, setDateRange] = React.useState(getDefaultRange());

  // 搜索条件（不含时间）
  const [search, setSearch] = React.useState({ userName: '', equipmentNo: '', type: undefined });

  // 分页与加载
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [loading, setLoading] = React.useState(false);

  // 模拟告警数据（批量生成近30天的随机记录）
  const [allRecords] = React.useState(() => {
    const userNames = ['张三','李四','王五','赵六','小明','小红','小王','小李','小赵','小周'];
    const equipmentNos = ['A1-001','B3-210','C2-045','D9-077','E5-120','F7-331','G4-220','H8-450','J9-035','K6-777'];
    const aisles = ['A01','A02','B01','C03','D01','D08','H12','M02','T01','T03'];
    const typeInfos = {
      1: ['电机转动异常，需检修','电机启动失败','机械卡滞，需人工处理','故障恢复，状态正常'],
      2: ['货道无货，请及时补货','缺货提醒：某商品已售罄','进货提醒：库存不足','补货完成，库存正常'],
      3: ['温度传感器异常读数','温控模块通讯异常','温度超限，请检查制冷','温度恢复正常'],
      4: ['门禁被非法打开','柜门未关紧，存在安全隐患','门磁传感异常','门禁恢复正常'],
    };

    const list = [];
    const recordCount = 120; // 生成 120 条模拟记录
    for (let i = 0; i < recordCount; i++) {
      const type = 1 + Math.floor(Math.random() * 4); // 1-4
      const u = userNames[Math.floor(Math.random() * userNames.length)];
      const eq = equipmentNos[Math.floor(Math.random() * equipmentNos.length)];
      const aisle = aisles[Math.floor(Math.random() * aisles.length)];
      const dayOffset = Math.floor(Math.random() * 30); // 最近30天
      const hour = Math.floor(Math.random() * 24);
      const minute = Math.floor(Math.random() * 60);
      const second = Math.floor(Math.random() * 60);
      const dt = dayjs().subtract(dayOffset, 'day').hour(hour).minute(minute).second(second);
      const createTime = dt.format('YYYY-MM-DD HH:mm:ss');
      const codePrefix = { 1: 'E', 2: 'S', 3: 'T', 4: 'L' }[type];
      const code = `${codePrefix}${String(1 + Math.floor(Math.random() * 199)).padStart(3, '0')}`;
      const infoPool = typeInfos[type];
      const info = infoPool[Math.floor(Math.random() * infoPool.length)];
      const orderNumber = `ORD-${dt.format('YYYYMMDD')}-${String(1 + Math.floor(Math.random() * 999)).padStart(3, '0')}`;

      list.push({
        id: 1000 + i,
        userName: u,
        equipmentNo: eq,
        type,
        aisleNo: aisle,
        orderNumber,
        code,
        info,
        createTime,
      });
    }
    return list;
  });

  // 过滤与分页
  const filtered = React.useMemo(() => {
    const [start, end] = dateRange || [];
    const startTs = start ? start.valueOf() : undefined;
    const endTs = end ? end.valueOf() : undefined;
    return allRecords.filter(r => {
      if (search.userName && !String(r.userName).includes(search.userName)) return false;
      if (search.equipmentNo && !String(r.equipmentNo).includes(search.equipmentNo)) return false;
      if (search.type !== undefined && search.type !== '' && String(r.type) !== String(search.type)) return false;
      if (startTs && endTs) {
        const ts = dayjs(r.createTime).valueOf();
        if (ts < startTs || ts > endTs) return false;
      }
      return true;
    });
  }, [allRecords, search, dateRange]);

  const pagedData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  // 模拟加载动画
  React.useEffect(() => {
    setLoading(true);
    const timer = setTimeout(() => setLoading(false), 200);
    return () => clearTimeout(timer);
  }, [pageIndex, pageSize, search, dateRange]);

  const columns = [
    { title: '用户名称', dataIndex: 'userName', width: 250, align: 'center' },
    { title: '设备编号', dataIndex: 'equipmentNo', width: 150, align: 'center' },
    { title: '告警类型', dataIndex: 'type', width: 150, align: 'center', render: (v) => getLabel(v) },
    { title: '货道编号', dataIndex: 'aisleNo', width: 120, align: 'center' },
    { title: '订单号', dataIndex: 'orderNumber', width: 170, align: 'center' },
    { title: '告警码', dataIndex: 'code', width: 150, align: 'center' },
    { title: '告警信息', dataIndex: 'info', ellipsis: true },
    { title: '告警时间', dataIndex: 'createTime', width: 160, align: 'center' },
  ];

  const onSearch = async () => {
    const values = await form.validateFields();
    setSearch({
      userName: values.userName || '',
      equipmentNo: values.equipmentNo || '',
      type: values.type !== undefined ? values.type : undefined,
    });
    setPageIndex(1);
  };

  const onReset = () => {
    form.resetFields();
    setSearch({ userName: '', equipmentNo: '', type: undefined });
    setDateRange(getDefaultRange());
    setPageIndex(1);
  };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      {/* 搜索条件 */}
      <Card variant="borderless" title="告警搜索">
        <Form form={form} layout="inline" style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <Form.Item label="时间范围">
            <DatePicker.RangePicker
              value={dateRange}
              onChange={(v) => setDateRange(v)}
              showTime={{ format: 'HH:mm:ss' }}
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>
          <Form.Item name="userName" label="用户名称">
            <Input allowClear placeholder="请输入用户名称" style={{ width: 220 }} />
          </Form.Item>
          <Form.Item name="equipmentNo" label="设备编号">
            <Input allowClear placeholder="请输入设备编号" style={{ width: 220 }} />
          </Form.Item>
          <Form.Item name="type" label="告警类型">
            <Select allowClear style={{ width: 220 }} options={alarmTypeList} placeholder="请选择告警类型" />
          </Form.Item>
          <Space>
            <Button type="primary" onClick={onSearch}>查询</Button>
            <Button onClick={onReset}>重置</Button>
          </Space>
        </Form>
      </Card>

      {/* 列表 */}
      <Card variant="borderless" title="告警记录" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pagedData}
          columns={columns}
          scroll={{ y: 638 }}
          pagination={{
            current: pageIndex,
            pageSize,
            total: filtered.length,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            onChange: (pi, ps) => {
              setPageIndex(pi);
              setPageSize(ps);
            },
          }}
        />
      </Card>
    </div>
  );
}